import { Directive, ElementRef, Input, OnInit, OnDestroy, Renderer2 } from '@angular/core';
import { AmChartsService } from "@amcharts/amcharts3-angular";

@Directive({
    selector: '[mapChart]'
})

export class MapChartDirective implements OnInit, OnDestroy {
    private chart: any;
    private _chartData: any[] = [];
    private _currentCompany: string;
    private _currentEvent: string;

    @Input() chartID: string;
    @Input() currentCompany: string;
    @Input() currenEvent: string;

    @Input() set chartData(value: any[]) {

        var targetSVG = "M10 16A6 6 0 1 1 10.001 16M10 14A4 4 0 1 0 9.999 14";

        if (value) {
            var locations = [];
            value.forEach(element => {
                locations.push({
                    svgPath: targetSVG,
                    zoomLevel: 5,
                    scale: 0.5,
                    title: element.address,
                    latitude: element.latitude,
                    longitude: element.longitude
                });
            });
            this._chartData = locations;
            if (this.chart) {
                this.AmCharts.updateChart(this.chart, () => {
                    this.chart.dataProvider = this._chartData;
                });
            }
        }
    }

    constructor(private el: ElementRef, private AmCharts: AmChartsService, private renderer: Renderer2) { }

    ngOnInit() {
        setTimeout(() => {
            this.chart = this.AmCharts.makeChart(this.chartID, {
                type: "map",
                theme: "light",
                projection: "miller",          
                areasSettings: {
                unlistedAreasColor: "#555"
                },
                mouseWheelZoomEnabled: false,
                zoomOnDoubleClick: false,
                dragMap: false,
                zoomControl: {
                    homeButtonEnabled: false,
                    panControlEnabled: false,
                    zoomControlEnabled: false
                },
                export: {
                    enabled: false
                },
                dataProvider: {
                map: "worldLow",
                images: this._chartData
                }
            });
        });
    }

    ngOnDestroy() {
        this.AmCharts.destroyChart(this.chart);
    }

    ring(x, y, ir, or): string {
        return 'M'+x+' '+(y+or)+'A'+or+' '+or+' 0 1 1 '+(x+0.001)+' '+(y+or) + 'M'+x+' '+(y+ir)+'A'+ir+' '+ir+' 0 1 0 '+(x-0.001)+' '+(y+ir);
    }
}